import { FC } from "react"
import { saveAs } from "file-saver"
import { myFunction } from "./header"
import ExcelJS from "exceljs"
import { useNavigate } from "react-router-dom"

const handle = (datas: any) => {
  const data: any = {
    piantiehou: {
      上反: [],
      下反: [
        { name: 2, age: 23 },
        { name: 2, age: 23 },
      ],
      透射: [
        { name: 3, age: 23 },
        { name: 3, age: 23 },
        { name: 3, age: 23 },
      ],
    },
    pol: {
      KE透射: [
        // { name: 4, age: 23 },
        // { name: 4, age: 23 },
        // { name: 4, age: 23 },
        // { name: 4, age: 23 },
      ],
      其他透射: [
        { name: 5, age: 23 },
        { name: 5, age: 23 },
        { name: 5, age: 23 },
        { name: 5, age: 23 },
        { name: 5, age: 23 },
      ],
      不知道: [
        { name: 6, age: 23 },
        { name: 6, age: 23 },
        { name: 6, age: 23 },
        { name: 6, age: 23 },
        { name: 6, age: 23 },
      ],
    },
  }
  Object.keys(data).forEach((item, item_index) => {
    const dataKey = data[item]
    let firstNonEmptyArray: any = null
    Object.keys(dataKey).forEach((yy, yi) => {
      if (dataKey[yy].length) {
        if (firstNonEmptyArray === null) {
          firstNonEmptyArray = dataKey[yy]
        }
      }
    })
    if (firstNonEmptyArray !== null) {
      firstNonEmptyArray[0]["onSpanRow"] = 14
    }
  })

  console.log(`data`, data)
}

const handleExcel = async () => {
  const workbook = new ExcelJS.Workbook()
  workbook.creator = "Me"
  workbook.lastModifiedBy = "Her"
  workbook.created = new Date(1985, 8, 30)
  workbook.modified = new Date()
  workbook.lastPrinted = new Date(2016, 9, 27)
  const worksheet = workbook.addWorksheet("My Sheet1")
  worksheet.columns = [
    {
      header: "panel ID",
      key: "panelId",
    },
    {
      header: "工站",
      key: "site",
    },
    {
      header: "工位",
      key: "station",
    },
    {
      header: "缺陷类型",
      key: "className",
    },
    {
      header: "复盘结果(NG/OK)",
      key: "reslut",
    },
    {
      header: "过检(Y/N)",
      key: "over",
    },
    {
      header: "漏检(Y/N)",
      key: "pass",
    },
  ]

  // 添加数据验证到指定列
  // 添加数据验证到每个单元格（包括空单元格）
  for (let row = 1; row <= 10000; row++) {
    const cell1 = worksheet.getCell(row, 1)
    cell1.dataValidation = {
      type: "textLength",
      operator: "greaterThan",
      formulae: [0],
      allowBlank: false, // 禁止留空
      showErrorMessage: true,
      errorTitle: "输入错误",
      error: "panel id不能为空",
    }
    const cell = worksheet.getCell(row, 5)
    cell.dataValidation = {
      type: "list",
      allowBlank: false,
      formulae: ['"NG,OK"'],
      showErrorMessage: true,
      errorTitle: "输入错误",
      error: "请输入有效的值",
    }
    const cell6 = worksheet.getCell(row, 6)
    cell6.dataValidation = {
      type: "list",
      allowBlank: true,
      formulae: ['"N,Y"'],
      showErrorMessage: true,
      errorTitle: "输入错误",
      error: "请输入有效的值",
    }

    const cell7 = worksheet.getCell(row, 7)
    cell7.dataValidation = {
      type: "list",
      allowBlank: true,
      formulae: ['"N,Y"'],
      showErrorMessage: true,
      errorTitle: "输入错误",
      error: "请输入有效的值",
    }
  }
  worksheet.getCell("A2  ").dataValidation = {
    type: "list",
    operator: "notEqual",
    allowBlank: false,
    showErrorMessage: true,
    formulae: ['"One,Two,Three,Four"'],
    errorStyle: "error",
    errorTitle: "Five",
    error: "The value must not be Five",
  }

  const buffer = await workbook.xlsx.writeBuffer()
  const blob = new Blob([buffer], {
    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  })

  // 保存 Blob 对象到本地文件
  saveAs(blob, "my-workbook.xlsx")
}

const handleDatas = () => {
  const datas = [
    { stie: "偏贴后", station: "上反", className: "110", notgood: "N" },
    { stie: "偏贴后", station: "上反", className: "110", notgood: "N" },
    { stie: "偏贴后", station: "上反", className: "110", notgood: "Y" },
    { stie: "偏贴后", station: "下反", className: "134", notgood: "Y" },
    { stie: "pol", station: "KE", className: "123", notgood: "N" },
    { stie: "pol", station: "KE", className: "123", notgood: "Y" },
    { stie: "pol", station: "KE", className: "110", notgood: "Y" },
    { stie: "pol", station: "KE", className: "", notgood: "Y" },
    { stie: "pol", station: "", className: "110", notgood: "Y" },
    { stie: "", station: "KE", className: "110", notgood: "Y" },
  ]

  const config = [
    {
      piantiehou: {
        site: "偏贴后",
        station: {
          上反: {
            children: [110, 13, 154, 135],
          },
          下反: {
            children: [118, 143, 134, 1351],
          },
        },
      },

      pol: {
        site: "pol",
        station: {
          KE: { children: [110, 124, 123] },
        },
      },
    },
  ]

  // 根据 'stie'、'station' 和 'className' 属性分组
  const groups: any[] = datas.reduce((result: any, item: any) => {
    const key = `${item.stie}_${item.station}_${item.className}`
    if (!result[key]) {
      result[key] = []
    }
    result[key].push(item)
    return result
  }, {})

  // 只保留每组中的最后一条数据
  const result = Object.values(groups).map((group) => group[group.length - 1])

  console.log(result)

  // 遍历数据，将每条记录与对应关系进行匹配
  let item: {
    stie: string
    station: string
    className: string
    notgood: string
  }
  // for (item of result) {
  //   let matched = false
  //   for (const groups of config) {
  //     const site = groups[item.stie]
  //     if (site && site.site === item.stie) {
  //       const station = site.station[item.station]
  //       if (station && station.children.includes(parseInt(item.className))) {
  //         matched = true
  //         break
  //       }
  //     }
  //   }
  //   console.log(`数据 ${JSON.stringify(item)} 是否匹配：${matched}`)
  // }
}

// 这个页面根据业务来自行设计吧
const Home: FC = () => {
  const navigates = useNavigate()
  const text = () => {
    navigates("/nested_table")
  }

  const tt = () => {
    myFunction(navigates)
  }
  return (
    <div>
      <button onClick={handle}>点击</button>
      <button onClick={handleExcel}>点击下载excel模板</button>
      <button onClick={tt}>点击跳转</button>
      <button onClick={handleDatas}>点击处理数据</button>
      <button onClick={text}>测试</button>
    </div>
  )
}
export default Home
